package com.rt.easyjava.common.dozer.converter;

import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.utils.others.InvokeMethodUtils;
import com.rt.easyjava.common.utils.others.StringUtils;
import org.dozer.DozerConverter;

import java.util.Map;

/**
 * 枚举类型在dozer中的转换工具类
 * Dto中用Object接收json对象，结构如：deleteflag：{'key':1, 'name':'有效'}, 前端展示处理如：row.deleteflag.name
 * Created by wxy on 2020/4/8.
 */
public class EnumConverter extends DozerConverter<Integer,Object> {


    public EnumConverter() {
        super(Integer.class, Object.class);
    }

    // Bean -> Dto
    @Override
    public Object convertTo(Integer source, Object destination) {
        if(source == null) {
            JSONObject json = new JSONObject();
            json.put("id", 0);
            json.put("name", "");
            return json;
        }
        try{
            String enumClass = getParameter();
            Object object = InvokeMethodUtils.invokeStaticMethod(enumClass,"explain", source);
            String name = String.valueOf(object);
            JSONObject json = new JSONObject();
            json.put("id", source);
            json.put("name", name);
            return json;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Dto -> Bean
    @Override
    public Integer convertFrom(Object source, Integer destination) {
        if(StringUtils.isNull(source)) return null; // mapper转换dto->bean作查询条件时，非查询条件需要为null
        if("{}".equals(source)) return null;
        // 行内编辑保存时，传过来的是一个map: {id=1, name=xxx}
        if(source instanceof Map) {
            return Integer.parseInt(((Map)source).get("id").toString());
        }
        return Integer.parseInt(source.toString());
    }



}
